package com.sz.app.oss.api.system;

import com.sz.app.oss.constants.MessagesCodes;
import com.sz.app.oss.constants.Permissions;
import com.sz.biz.app.web.BaseController;
import com.sz.common.base.dto.QResultDto;
import com.sz.common.base.dto.ResultDto;
import com.sz.common.base.exception.BizException;
import com.sz.common.core.system.dto.OrgUserDto;
import com.sz.common.core.system.dto.UserDto;
import com.sz.common.core.system.service.UserService;
import io.swagger.annotations.*;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.text.ParseException;
import java.util.List;

/**
 * Function: OrgController <br>
 * Author: wentao.chang <br>
 * Date: 2016-10-31 10:04:00
 */
@RestController
@RequestMapping("${api}/sys/users")
@Api(description = " ", tags = "003、用户管理")
public class UserController extends BaseController {

    @Autowired
    private UserService userService;

    /**
     * 获取用户列表
     *
     * @throws BizException ex
     */
    @ApiOperation(value = "搜索用户", notes = "搜索用户，返回用户列表，支持分页")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "orgid", value = "组织id",
                    required = true, dataType = "int", paramType = "path"),
            @ApiImplicitParam(name = "q", value = "查询的关键字",
                    dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "isIncludeSubOrg", value = "是否包含子组织的用户",
                    dataType = "boolean", paramType = "query"),
            @ApiImplicitParam(name = "locked", value = "是否锁定-1全部0未锁定1已锁定",
                    dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "pageIndex", value = "分页 默认第一页",
                    dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "页面大小",
                    dataType = "int", paramType = "query")})
    @RequestMapping(value = "/search/{orgid}", method = {RequestMethod.GET})
    public ResultDto getUsers(@PathVariable int orgid,
                              @RequestParam(defaultValue = "") String q,
                              @RequestParam(defaultValue = "true") boolean isIncludeSubOrg,
                              @RequestParam(defaultValue = "1") int pageIndex,
                              @RequestParam(defaultValue = "0") int locked,
                              @RequestParam(name = "pageSize", defaultValue = "10") int pageSize)
            throws BizException {
        return userService.findByFilterListPage(orgid, locked, q, isIncludeSubOrg, pageIndex, pageSize);
    }

    /**
     * 获取用户列表
     *
     * @throws BizException ex
     */
    @ApiOperation(value = "搜索用户不通过电话搜索", notes = "搜索用户不通过电话搜索，返回用户列表，支持分页")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "orgid", value = "组织id",
                    required = true, dataType = "int", paramType = "path"),
            @ApiImplicitParam(name = "q", value = "查询的关键字",
                    dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "isIncludeSubOrg", value = "是否包含子组织的用户",
                    dataType = "boolean", paramType = "query"),
            @ApiImplicitParam(name = "locked", value = "是否锁定-1全部0未锁定1已锁定",
                    dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "pageIndex", value = "分页 默认第一页",
                    dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "页面大小",
                    dataType = "int", paramType = "query")})
    @RequestMapping(value = "/searchbynameandid/{orgid}", method = {RequestMethod.GET})
    public ResultDto getUsersByNameOrId(@PathVariable int orgid,
                              @RequestParam(defaultValue = "") String q,
                              @RequestParam(defaultValue = "true") boolean isIncludeSubOrg,
                              @RequestParam(defaultValue = "1") int pageIndex,
                              @RequestParam(defaultValue = "0") int locked,
                              @RequestParam(name = "pageSize", defaultValue = "10") int pageSize)
            throws BizException {
        return userService.findByFilterNameOrIdListPage(orgid, locked, q, isIncludeSubOrg, pageIndex, pageSize);
    }

    /**
     * 用户模糊匹配无分页
     *
     * @throws BizException ex
     */
    @ApiOperation(value = "用户模糊匹配无分页", notes = "用户模糊匹配 不支持分页最多返回20条")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "q", value = "查询的关键字", dataType = "string", paramType = "query")
    })
    @RequestMapping(value = "/search", method = {RequestMethod.GET})
    public ResultDto getUsersNoPage(@RequestParam(defaultValue = "") String q) throws BizException {
        q = q.trim();
        return userService.findByFilter(q);
    }
    /**
     * 用户模糊匹配
     *
     * @throws BizException ex
     */
    @ApiOperation(value = "用户模糊匹配", notes = "用户模糊匹配 不支持分页最多返回20条")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "q", value = "查询的关键字", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "pageIndex", value = "分页 默认第一页", dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "页面大小", dataType = "int", paramType = "query")}) 
    @RequestMapping(value = "/short", method = {RequestMethod.GET})
    public ResultDto getUsersWithPage(@RequestParam(defaultValue = "") String q  ,
                                      @RequestParam(defaultValue = "1") int pageIndex, 
                                      @RequestParam(name = "pageSize", defaultValue = "10") int pageSize) throws BizException {
        q = q.trim();
        return userService.findShortListPage(q,pageIndex,pageSize);
    }

    /**
     * 用户模糊匹配-BD职位
     *
     * @throws BizException ex
     */
    @ApiOperation(value = "用户模糊匹配-BD职位", notes = "用户模糊匹配 支持分页")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "q", value = "查询的关键字", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "分页", dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "pageIndex", value = "分页", dataType = "int", paramType = "query")
    })
    @RequestMapping(value = "/bd/search", method = {RequestMethod.GET})
    public ResultDto getBdUsers(@RequestParam(defaultValue = "") String q,
                                @RequestParam(defaultValue = "1") int pageIndex,
                                @RequestParam(defaultValue = "20") int pageSize) throws BizException {
        q = q.trim();
        return userService.findBdsByFilter(q,pageIndex,pageSize);
    }

    /**
     * 新建一个用户
     *
     * @throws Exception ex
     */
    @ApiOperation(value = "新建用户", notes = "-<br>权限：" + Permissions.SYS_MGT_USER)
    @ApiImplicitParams({@ApiImplicitParam(name = "userDto", value = "提交的用户信息\r\n"
            + "address,description,email,\r\n"
            + "fullName,mobilephone,\r\n" + "password,userCode,birthday,\r\n"
            + "sex:f|m,positionCode,orgId", required = true, dataType = "UserDto", paramType = "body")})
    @RequestMapping(value = "", method = {RequestMethod.POST})
    @RequiresPermissions(value = {Permissions.SYS_MGT_USER})
    public ResultDto saveUser(@RequestBody @Validated UserDto userDto) throws Exception {
        int userId = userService.saveUser(userDto);
        ResultDto dto = getOperateSuccessDto(MessagesCodes.USER_ADDNEW_SUCCESS);
        dto.setData(userId);
        return dto;
    }

    /**
     * 修改一个用户
     *
     * @throws Exception ex
     */
    @ApiOperation(value = "修改用户", notes = "-<br>权限：" + Permissions.SYS_MGT_USER)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "修改用户的id ",
                    required = true, dataType = "int", paramType = "path"),
            @ApiImplicitParam(name = "userDto", value = "提交的用户信息\r\n " + "address,description,email,\r\n"
                    + "fullName,mobilephone,\r\n" + "password,userCode,birthday,\r\n"
                    + "sex:f|m,positionCode,orgId", required = true, dataType = "UserDto", paramType = "body")})

    @RequestMapping(value = "/{id}", method = {RequestMethod.PUT})
    @RequiresPermissions(value = {Permissions.SYS_MGT_USER})
    public ResultDto updateUser(@PathVariable int id, @RequestBody @Validated UserDto userDto) throws Exception {
        userService.updateUser(id, userDto);
        ResultDto dto = getUpdateSuccessDto(MessagesCodes.MODULE_USER);
        dto.setData(id);
        return dto;
    }

    /**
     * 重置用户密码
     *
     * @throws Exception ex
     */
    @ApiOperation(value = "重置用户密码", notes = "-<br>权限：" + Permissions.SYS_MGT_USER)
    @RequestMapping(value = "/resetpasswd", method = {RequestMethod.POST})
    @RequiresPermissions(value = {Permissions.SYS_MGT_USER})
    public ResultDto resetpasswd(
            @ApiParam(value = "用户的ids", required = true) @RequestBody List<Integer> userids) throws Exception {
        userService.resetUsersPasswd(userids);
        ResultDto dto = getOperateSuccessDto(MessagesCodes.USER_RESET_PASSWORD_SUCCESS);
        dto.setData(userids);
        return dto;
    }

    /**
     * 获取单个用户
     */
    @ApiOperation(value = "根据id获取用户", notes = "-<br>权限：" + Permissions.SYS_MGT_USER)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "用户的id ", required = true, dataType = "int", paramType = "path")})
    @RequestMapping(value = "/{id}", method = {RequestMethod.GET})
    public ResultDto getUserById(@PathVariable int id) {

        ResultDto resultDto = new ResultDto();
        resultDto.setData(userService.getUserById(id));
        return resultDto;
    }

    /**
     * 删除一个用户 非物理删除 打标志 不允许登录
     *
     * @throws Exception ex
     */
    @ApiOperation(value = "删除一个用户", notes = "非物理删除 打标志 不允许登录<br>权限：" + Permissions.SYS_MGT_USER)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "用户的id ", required = true, dataType = "int", paramType = "path")})
    @RequestMapping(value = "/{id}", method = {RequestMethod.DELETE})
    @RequiresPermissions(value = {Permissions.SYS_MGT_USER})
    public ResultDto deleteUser(@PathVariable int id) throws Exception {
        userService.deleteUserById(id);
        ResultDto dto = getDeleteSuccessDto(MessagesCodes.MODULE_USER);
        dto.setData(id);
        return dto;
    }

    /**
     * 批量删除用户 非物理删除 打标志 不允许登录
     *
     * @throws Exception ex
     */
    @ApiOperation(value = "批量删除用户", notes = "非物理删除 打标志 不允许登录<br>权限：" + Permissions.SYS_MGT_USER)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ids", value = "用户的ids",
                    required = true, dataType = "string", paramType = "body")})
    @RequestMapping(value = "/deletions", method = {RequestMethod.POST})
    @RequiresPermissions(value = {Permissions.SYS_MGT_USER})
    public ResultDto deleteUsers(@RequestBody String[] ids) throws Exception {
        userService.deleteUsersById(ids);
        return getDeleteSuccessDto(MessagesCodes.MODULE_USER);
    }

    /**
     * 锁定用户 不允许登录
     *
     * @throws Exception ex
     */
    @ApiOperation(value = "锁定用户", notes = "不允许登录<br>权限：" + Permissions.SYS_MGT_USER)
    @RequestMapping(value = "/lock", method = {RequestMethod.POST})
    @RequiresPermissions(value = {Permissions.SYS_MGT_USER})
    public ResultDto lockUser(@ApiParam(value = "用户的ids", required = true) @RequestBody List<Integer> ids)
            throws Exception {
        userService.lockUserByUserIds(ids);
        ResultDto dto = getOperateSuccessDto(MessagesCodes.USER_LOCK_SUCCESS);
        dto.setData(ids);
        return dto;
    }

    /**
     * 解锁用户
     *
     * @throws Exception ex
     */
    @ApiOperation(value = "解锁定用户", notes = "允许登录<br>权限：" + Permissions.SYS_MGT_USER)
    @RequestMapping(value = "/unlock", method = {RequestMethod.POST})
    @RequiresPermissions(value = {Permissions.SYS_MGT_USER})
    public ResultDto unLockUser(@RequestBody List<Integer> ids) throws Exception {
        userService.unLockUserByUserIds(ids);
        ResultDto dto = getOperateSuccessDto(MessagesCodes.USER_UNLOCK_SUCCESS);
        dto.setData(ids);
        return dto;
    }


    /**
     * 用户删除角色
     *
     * @throws BizException   ex
     * @throws ParseException ex
     */
    @ApiOperation(value = "用户删除角色", notes = "用户删除角色<br>权限：" + Permissions.SYS_MGT_USER)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "用户的id ",
                    required = true, dataType = "int", paramType = "path"),
            @ApiImplicitParam(name = "roleId", value = "角色的id",
                    required = true, dataType = "int", paramType = "path")})
    @RequestMapping(value = "/{userId}/removerole/{roleId}", method = {RequestMethod.DELETE})
    @RequiresPermissions(value = {Permissions.SYS_MGT_USER})
    public ResultDto removeUserRole(@PathVariable int userId, @PathVariable int roleId)
            throws BizException, ParseException {
        userService.removeUserRole(userId, roleId);
        ResultDto dto = getDeleteSuccessDto(MessagesCodes.MODULE_USER);
        dto.setData(userId);
        return dto;
    }

    /**
     * 用户移动组织
     */
    @ApiOperation(value = "用户移动组织", notes = "用户移动组织 只支持组织机构不支持用户组<br>权限：" + Permissions.SYS_MGT_USER)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "targetorgid", value = "移动到哪个组织",
                    required = true, dataType = "int", paramType = "path"),
            @ApiImplicitParam(name = "userIds", value = "用户的id列表",
                    required = true, dataType = "string", paramType = "body")})
    @RequestMapping(value = "/moveorg/{targetorgid}", method = {RequestMethod.POST})
    @RequiresPermissions(value = {Permissions.SYS_MGT_USER})
    public ResultDto moveUsersOrg(@PathVariable int targetorgid,
                                  @RequestBody String[] userIds) throws BizException, ParseException {
        userService.moveUsersOrg(targetorgid, userIds);
        return getOperateSuccessDto(MessagesCodes.USER_MOVE_ORG_SUCCESS);
    }

    /**
     * 异步校验工号
     */
    @ApiOperation(value = "异步校验工号", notes = "异步校验工号")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "code", value = "工号",
                    required = true, dataType = "string", paramType = "query")})
    @RequestMapping(value = "/checkcode", method = {RequestMethod.GET})
    public ResultDto userCodeCheck(@RequestParam String code) {
        userService.userCodeCheck(code);
        return new ResultDto();
    }

    /**
     * 异步校验邮箱
     */
    @ApiOperation(value = "异步校验邮箱", notes = "异步校验邮箱")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "email", value = "邮箱",
                    required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "userId", value = "用户id 修改时传id 新增时传空",
                    dataType = "int", paramType = "query")})
    @RequestMapping(value = "/checkemail", method = {RequestMethod.GET})
    public ResultDto userEmailCheck(@RequestParam String email,
                                    @RequestParam(required = false, defaultValue = "0") int userId) {
        userService.userEmailCheck(userId, email);
        return new ResultDto();
    }

    /**
     * 通过orgCode拿到用户
     */
    @ApiOperation(value = "通过orgCode查询", notes = "搜索用户，返回用户列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "orgCode", value = "组织 code",
                    required = true, dataType = "string", paramType = "query")})
    @RequestMapping(value = "/searchByOrgCode", method = {RequestMethod.GET})
    public ResultDto queryByOrgCode(@RequestParam String orgCode) {
        List<OrgUserDto> results = userService.findUserByOrgCode(orgCode);
        return new ResultDto(results);
    }

    /**
     * 通过orgCode拿到用户
     */
    @ApiOperation(value = "通过orgCode查询分页信息", notes = "搜索用户，返回用户列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "orgCode", value = "组织 code",
                    required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "q", value = "名称或者工号",
                    dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "pageIndex", value = "分页 默认第一页",
                    dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "页面大小",
                    dataType = "int", paramType = "query")
    })
    @RequestMapping(value = "/searchpagebyorgcode", method = {RequestMethod.GET})
    public QResultDto queryUserPage(@RequestParam(required = true) String orgCode,
                                    @RequestParam(required = false) String q,
                                    @RequestParam(required = false,defaultValue = "0") int pageIndex,
                                    @RequestParam(name = "pageSize", defaultValue = "10") int pageSize) {
        QResultDto results = userService.findByFilterOrgCodeListPage(orgCode, q, pageIndex, pageSize);
        return results;
    }
}
